#include "outputrenderer.h"
#include "stitcher.h"
#include "commandlineoptions.h"
#include <algorithm>
#include "inputimage.h"
#include <boost/foreach.hpp>
#include <Magick++.h>

using namespace cshotel;
using namespace std;
using namespace boost;
using namespace Magick;

string OutputRenderer::getTransformedVersionFileName(const string& fileName) {
    string prefix;
    if(CommandLineOptions::getInstance().getOutputFormat() == CommandLineOptions::TransformedFiles) {
        prefix = CommandLineOptions::getInstance().getOutputName();
    } else {
        prefix = CommandLineOptions::getInstance().getWorkingDirectory();
    }
    int dotIndex = fileName.rfind('.');
    if(dotIndex == string::npos) {
        return prefix + fileName + "_transformed.png";
    }
    return prefix + fileName.substr(0, dotIndex) + "_transformed.png";
}

string OutputRenderer::getPanoramaFileName() {
    if(CommandLineOptions::getInstance().getOutputFormat() == CommandLineOptions::PanoramaFile) {
        return CommandLineOptions::getInstance().getOutputName() + ".jpg";
    } else {
        return CommandLineOptions::getInstance().getWorkingDirectory() + "panorama.jpg";
    }
}

string OutputRenderer::getThumbnailFileName() {
    return CommandLineOptions::getInstance().getOutputName() +  CommandLineOptions::getInstance().getThumbnailSuffix() + ".jpg";
}

void OutputRenderer::createThumbnail() {
    string panoramaName = getPanoramaFileName();
    string thumbName = getThumbnailFileName();
    Image thumb(panoramaName.c_str());
    int panoramaWidth = thumb.size().width();
    int panoramaHeight = thumb.size().height();
    int thumbSize = CommandLineOptions::getInstance().getThumbnailSize();
    if(panoramaWidth > panoramaHeight) {
        int newWidth = panoramaWidth * (static_cast<double>(thumbSize) / panoramaHeight);
        thumb.scale(Geometry(newWidth, thumbSize));
        int leftOffset = (newWidth - thumbSize) / 2;
        thumb.crop(Geometry(thumbSize, thumbSize, leftOffset, 0));
    } else {
        int newHeight = panoramaHeight * (static_cast<double>(thumbSize) / panoramaWidth);
        thumb.scale(Geometry(thumbSize, newHeight));
        int topOffset = (newHeight - thumbSize) / 2;
        thumb.crop(Geometry(thumbSize, thumbSize, 0, topOffset));
    }
    thumb.write(thumbName.c_str());
}

string OutputRenderer::buildDeepZoomConverterCommand() {
    ostringstream command;
    command << "java ";
    command << CommandLineOptions::getInstance().getJavaOptions();
    command << " -jar ";
    command << CommandLineOptions::getInstance().getDeepZoomConverterJar();
    command << " ";
    command << CommandLineOptions::getInstance().getDeepZoomConverterOptions();
    command << " -o ";
    command << CommandLineOptions::getInstance().getOutputName();
    command << " ";
    command << getPanoramaFileName();
    return command.str();
}
